#include<iostream>
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include<string>
#include<unistd.h>
#include<mutex>
using namespace std;


struct Tickets
{

    Tickets()
    {
        pthread_mutex_init(&mtx,nullptr);
    }

    //抢票函数
    bool GetTickets()
    {
        bool ret = true;
        //此处抢票，需要加锁
        //pthread_mutex_lock(&mtx);
        mtx2.lock();
        if(tickets > 0)
        {
            usleep(1000);
            cout << "我是["<<pthread_self()<<"],tickets:"<<tickets<<endl;
            tickets--;
            printf("");
        }
        else
        {
            cout <<"票已经空了"<<endl;
            ret = false;
        }
        //pthread_mutex_unlock(&mtx);//解锁
        mtx2.unlock();
        return ret;
    }

    ~Tickets()
    {
        pthread_mutex_destroy(&mtx);
    }

    int tickets = 1000;
    pthread_mutex_t mtx;//系统原生锁
    mutex mtx2;//C++语言库锁
};


void* ThreadRoutin(void* args)
{
    Tickets* t = (Tickets*)args;
    while(true)
    {
        if(!t->GetTickets())
        {
            break;
        }
    }
}

int main()
{
    pthread_t tid[5];
    Tickets t;
    for(int i = 0;i < 5 ;i++)
    {
        int* id = new int(i);
        pthread_create(tid+i,nullptr,ThreadRoutin,(void*)&t);
    }
    for(int i = 0;i < 5 ;i++)
    pthread_join(tid[i],nullptr);
    return 0;
}
